# -*- coding: utf-8 -*-
# @Time    : 2020-10-19 13:53
# @Author  : Daniel

import base64
import hashlib
import hmac
import json
import time
import urllib.parse

import requests

# 机器人说明文档 https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq

timestamp = str(round(time.time() * 1000))
secret = 'abcdef'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

# 使用自己的token, 通过钉钉的群机器人中获得
# token有几种认证模式，[mark] 使用了关键字认证，可以根据自己需要替换
token = '****************'

url = 'https://oapi.dingtalk.com/robot/send?' \
      'access_token=%s' \
      '&timestamp=%s' \
      '&sign=%s' % (token, timestamp, sign)

msg = {
    "msgtype": "text",
    "text": {
        "content": "[mark] test"
    },
    "at": {
        "isAtAll": True
    }
}

header = {
    "Content-Type": "application/json",
    "Charset": "UTF-8"}

msg_json = json.dumps(msg)
info = requests.post(url=url, data=msg_json, headers=header)
# print(info.text)
